package com.open.party.cloud.view.freePhoto

import android.content.Intent
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.TextView
import androidx.appcompat.widget.AppCompatSpinner
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import cn.android.x.model.data.ResultInfo
import cn.sinothk.map.amap.base.MapCallback
import cn.sinothk.map.amap.location.AMapLocate
import cn.sinothk.map.amap.location.AMapLocationEntity
import com.jiangyy.easydialog.CommonDialog
import com.open.party.cloud.R
import com.open.party.cloud.model.*
import com.open.party.cloud.model.data.CodeValue
import com.open.party.cloud.view.base.TownshipUnitSelectActivity
import com.open.party.cloud.view.freePhoto.adpater.ImageSelectedShowAdapter
import com.open.party.cloud.viewModel.FreePhotosViewModel
import com.sinothk.android.utils.XUtils
import com.sinothk.image.selected.ImgSelectEntity
import com.sinothk.image.selector.PhotoPreviewActivity
import com.sinothk.switchTabView.style1.UIUtil
import kotlinx.android.synthetic.main.free_photo_creator.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * <pre>
 *  创建:  梁玉涛 2019/3/24 on 14:27
 *  项目:
 *  描述:
 *  更新:
 * <pre>
 */
open class FreePhotosAddActivity : PhotosCreatorBaseActivity() {

    private var locationInfo: AMapLocationEntity? = null
    var viewModel: FreePhotosViewModel? = null

    override fun getLayoutResId(): Int = R.layout.free_photo_creator

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setViewTitle("发布随手拍", "发送") {
            submit()
        }

        viewModel = FreePhotosViewModel()
        bizId = ""

        setListener()

        initMap()
        setImg()
        initLevelView()
    }

    private fun setListener() {
        areaItem.setOnClickListener {
            // 选择所属区域
            XUtils.intent().openActivity(this, TownshipUnitSelectActivity::class.java)
                .requestCode(CodeValue.OrgTownSelectCode)
                .start()
        }
    }

    private fun initMap() {
        locRefresh.setOnClickListener {
            refreshLoc(true)
        }
        refreshLoc(false)
    }

    private fun refreshLoc(tip: Boolean) {
        if (tip) {
            showLoadingDialog("获取位置中...")
        }

        AMapLocate().locationOnce(this, object: MapCallback<AMapLocationEntity>{
            override fun onSuccess(locInfo: AMapLocationEntity) {
                locationInfo = locInfo
                if (locInfo.code == 0) {
                    locationInfoTv.text = XUtils.string().getNotNullValue(locInfo.address, "无位置信息")
                } else {
                    locationInfoTv.text = XUtils.string().getNotNullValue("获取失败")
                }

                if (tip) {
                    hideLoadingDialog()
                }
            }

            override fun onFail(msg: String?) {
            }
        })
    }

    private fun submit() {
        if (!XUtils.net().isConnected) {
            XUtils.toast().show(R.string.net_error)
            return
        }

        if (XUtils.string().isEmpty(lootDeptId) || XUtils.string().isEmpty(lootDeptName)) {
            XUtils.toast().show("请选择所属区域")
            return
        }

        if (levelBean == null) {
            XUtils.toast().show("请选择紧急程度")
            return
        }

        val describeStr: String = describeTv.text.toString()
        if (XUtils.string().isEmpty(describeStr)) {
            XUtils.toast().show("请输入描述内容")
            return
        }

        if (locationInfo == null) {
            XUtils.toast().show("请先刷新位置信息后提交")
            return
        }

        if (imgSelectList.size == 0) {
            XUtils.toast().show("请上传文件")
            return
        }

        val freePhotosVo = FreePhotosVo()
        freePhotosVo.questionFom = DictionaryBean("sb", "自主上报")
        // 附件返回 bizId
//        freePhotosVo.id = bizId
        // 定位位置
        freePhotosVo.longitude = locationInfo!!.longitude
        freePhotosVo.latitude = locationInfo!!.latitude
        freePhotosVo.questionAddress = locationInfo!!.address
        // 描述
        freePhotosVo.questionDesc = describeStr
        // 紧急程度
        freePhotosVo.worryLevel = levelBean
        // 区域
        freePhotosVo.lootDeptId = lootDeptId
        freePhotosVo.lootDeptName = lootDeptName
        freePhotosVo.claimUser = XUtils.string().getNotNullValue(claimUser)
        freePhotosVo.claimUserName = XUtils.string().getNotNullValue(claimUserName)

        // 处理图片
        val fileInfoList = ArrayList<FreePhotosFileBean>()
        for (imgBean in imgSelectList) {
            fileInfoList.add(FreePhotosFileBean(imgBean.url))
        }
        freePhotosVo.fileList = fileInfoList

        showLoadingDialog("正在提交")
        viewModel?.submitFreePhotos(freePhotosVo)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun eventBusSubmitCallback(result: ResultInfo<FreePhotosBean>) {
        if (result.eventType != "submitFreePhotos") {
            return
        }
        hideLoadingDialog()

        when (result.code) {
            ResultInfo.SUCCESS -> {
                XUtils.toast().show("提交成功")
                finish()
            }
            ResultInfo.TOKEN_OVERDUE -> {
            }
            else -> {
                XUtils.toast().show(result.msg)
            }
        }
    }

    private var mAlbumSelectedShowAdapter: ImageSelectedShowAdapter? = null

    private fun setImg() {
        mAlbumSelectedShowAdapter = ImageSelectedShowAdapter(this, 8)
        mRvAlbumSelected.layoutManager = GridLayoutManager(this, 4)
        mRvAlbumSelected.setHasFixedSize(true)
        mRvAlbumSelected.adapter = mAlbumSelectedShowAdapter

        mAlbumSelectedShowAdapter!!.setOnItemClickListener { _, position ->
            if (imgSelectList.size == position) {
                openSysCamera(BizType.FREE_PHOTO_DEAL_WITH_IMG)
            } else {
                //图片展示界面
                val imgList: ArrayList<String> = ArrayList()
                for (imgEntity: ImgSelectEntity in imgSelectList) {
                    imgList.add(imgEntity.filePath)
                }
                PhotoPreviewActivity.start(this@FreePhotosAddActivity, position, imgList)
            }
        }

        mAlbumSelectedShowAdapter!!.setItemDelClick { position ->
            dialog(position)
        }
    }

    override fun refreshImgView() {
        mAlbumSelectedShowAdapter?.setData(imgSelectList)
    }

    /*
     * Dialog对话框提示用户删除操作
     * position为删除图片位置
     */
    private fun dialog(position: Int) {
        CommonDialog.Builder(this)
            .setTitle("提示")
            .setMessage("确认移除已添加的图片吗？")
            .setPositiveButton("确认") {
                if (mAlbumSelectedShowAdapter!!.itemCount > 0) {
                    delPosition = position
                    // 删除服务器文件
                    delFileById(imgSelectList[position].id)
                }
            }.setNegativeButton("取消") {

            }.show()
    }

    private var delPosition: Int = 0

    override fun delFileSuccess() {
        // 移除展示数据
        imgSelectList.removeAt(delPosition)
        // 刷新界面
        mAlbumSelectedShowAdapter?.setData(imgSelectList)
        mAlbumSelectedShowAdapter?.notifyDataSetChanged()
    }

    // ===========================
    var levelBean: DictionaryBean? = null

    private fun initLevelView() {
        val levelBeanList = ArrayList<DictionaryBean>()
        // {pt:普通;jj:紧急;tj:特急}
        levelBeanList.add(DictionaryBean("PT", "普通"))
        levelBeanList.add(DictionaryBean("JJ", "紧急"))
        levelBeanList.add(DictionaryBean("TJ", "特急"))

        val levelValueList = ArrayList<String>()
        for (levelBean in levelBeanList) {
            levelValueList.add(levelBean.desc)
        }

        initSpinnerView(levelSpinner, levelValueList, object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(parent: AdapterView<*>?) {
            }

            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {

                if (view != null) {
                    val tv = view as TextView
                    tv.setTextColor(ContextCompat.getColor(this@FreePhotosAddActivity, R.color.page_content))
                    tv.paint.textSize = UIUtil.sp2px(this@FreePhotosAddActivity, 14f).toFloat()
                    tv.gravity = Gravity.CENTER
                    levelBean = levelBeanList[position]
                }
            }
        })
    }

    private var spinnerAdapter: ArrayAdapter<String>? = null

    private fun initSpinnerView(
        spinner: AppCompatSpinner, streetStrList: ArrayList<String>, itemSelectedListener: AdapterView.OnItemSelectedListener?
    ) {
        spinnerAdapter = ArrayAdapter(this, R.layout.street_spinner_item, streetStrList!!)
        spinnerAdapter!!.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.adapter = spinnerAdapter
        spinner.dropDownVerticalOffset = 100

        spinner.onItemSelectedListener = itemSelectedListener
    }

    // 所属区域
    private var lootDeptId = ""
    private var lootDeptName = ""
    private var claimUser = ""
    private var claimUserName = ""

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (data != null && CodeValue.ResultCodeSuccess == resultCode) {
            when (requestCode) {
                CodeValue.OrgTownSelectCode -> {
                    val bean: TownshipBean? = data.getSerializableExtra(CodeValue.Data) as TownshipBean
                    if (bean != null) {
                        lootDeptId = bean.id
                        lootDeptName = bean.name
                        claimUser = bean.managerId
                        claimUserName = bean.inLeader
                        areaValue.text = XUtils.string().getNotNullValue(lootDeptName)
                    } else {
                        XUtils.toast().show("选择信息不可用")
                    }

                    return
                }
            }
        }

        super.onActivityResult(requestCode, resultCode, data)
    }
}